package com.itheima.reggie.controller;

/**
 * @Author 669
 * @CreateDate 2023/3/1 14:33
 * @Version 1.0
 */
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;




    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据：{}",orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }


    /**
     * 后端获取订单信息
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    //http://localhost:8080/order/page?page=1&pageSize=10&number=544&beginTime=2023-03-29%2000%3A00%3A00&endTime=2023-04-15%2023%3A59%3A59
    public R<Page> getpage(Integer page, Integer pageSize, String number,
                           @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime beginTime,
                           @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")LocalDateTime endTime){
        LambdaQueryWrapper<OrdersDto> wrapper = new LambdaQueryWrapper<>();


        //分页构造器对象
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        Page<OrdersDto> dtoPage = new Page<>();

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据id进行like模糊查询
        wrapper.like(number!=null,Orders::getNumber,number);
        //g根据区间数据查询数据
        wrapper.between(beginTime!=null && endTime!=null,Orders::getOrderTime,beginTime,endTime);
        //添加排序条件，根据更新时间降序排列
        queryWrapper.orderByDesc(Orders::getOrderTime);

        orderService.page(pageInfo,queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        List<Orders> records = pageInfo.getRecords();

        List<OrdersDto> list = records.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            //对象拷贝
            BeanUtils.copyProperties(item,ordersDto);
            //分类id
            Long UserId = item.getUserId();
            //根据分类id查询分类对象
            User user = userService.getById(UserId);
            if(user != null){
                //分类名称
                String username = user.getName();
                ordersDto.setUserName(username);
            }
            return ordersDto;
        }).collect(Collectors.toList());
        log.info("获取订单信息成功");
        dtoPage.setRecords(list);
        return R.success(dtoPage);


    }

    /**
     * 获取用户订单信息
     * @param request
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> userPage(HttpServletRequest request, Integer page, Integer pageSize){
        //?page=1&pageSize=1
        Long userId = (Long) request.getSession().getAttribute("user");
        log.info("查询用户id为{}",userId.toString());

        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId,userId);
        //构造分页构造器
        Page pageInfo = new Page(page,pageSize);

        orderService.page(pageInfo,wrapper);
        log.info("查询用户订单信息成功");
        return R.success(pageInfo);
    }

    @PutMapping
    public R<String> editOrderDetail(@RequestBody Orders orders){
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getId,orders.getId());
        boolean b = orderService.update(orders, wrapper);
        log.info("修改订单信息为：{}",orders.toString());
        if (b){
            return R.success("订单信息修改成功！");

        }
        return R.error("订单信息修改失败");
    }


}